// 帮客房产
bangkeapp.controller('cbdctrl', 
	["$scope", "cbdService", "$state", "$stateParams", "$timeout",
		"$ionicLoading", "$ionicModal", "userinfoService", "$ionicPopup", 
			"$ionicPopover", "memberService", "fileurl", "commonService", 
    function($scope, cbdService, $state, $stateParams, $timeout,
    		$ionicLoading, $ionicModal, userinfoService, $ionicPopup,
    			$ionicPopover, memberService, fileurl, commonService) {
    		
    		// 查询是否支付密码, 如果设置, 跳转到支付页面, 如果没有, 跳转到设置密码页面
		memberService.issettedpaypwd().then(function(result) {
			if("M" == result.header.ResponseCode) {
				if(result.body.memberid == userinfoService.getUser().memberid &&
					"01" == result.body.handleStatus &&
					"Y" == result.body.operateStatus &&
					"0" == result.body.securepwdFlag) {

					// 打开设置密码界面
					$state.go('bangke.initpaypwd', {
						"inurl": "bangke.cbd"
					});

				} else if(result.body.memberid == userinfoService.getUser().memberid &&
					"01" == result.body.handleStatus &&
					"Y" == result.body.operateStatus &&
					"1" == result.body.securepwdFlag) {
					
    		$ionicLoading.show({
			content: 'Loading',
			animation: 'fade-in',
			showBackdrop: true,
			maxWidth: 200,
			showDelay: 0
		});
    		
    		// 房产会员购车款等信息
        $scope.buyinfo = {};
        // 房产会员个人信息
    		$scope.indexinit = {};
    		// 房产会员促成人信息
    		$scope.facilitate = {};
    		// 我的提现记录
    		$scope.drawalsrecord = {};
    		// 申请单
    		$scope.apply = {};
    		$scope.apply.lstFacilitatekey = [];
    		// 会员信息
    		$scope.member = userinfoService.getUser();
    		$scope.fileurl = fileurl;
    		$scope.applyshow = false;
    		$scope.initflag = [];
    		$scope.quitflag = false;
    		$scope.showactivemodal = function(){
	        // 激活模块
	        $ionicModal.fromTemplateUrl('templates/member/cbd/active.html', {
	            scope: $scope
	        }).then(function(modal) {
	        		$scope.activemodal = modal;
	        		$scope.activemodal.show();
	        		cbdService.registerqueryredpacket(userinfoService.getUser().memberid).then(function(result) {
					$scope.deduction = result.body.deduction;
					if (parseInt(result.body.redpacket) >= parseInt(result.body.deduction)) {
						// 显示选择推荐人div
						$scope.showactive = true;
					} else {
						// 积分不够无法激活
						$scope.showactive = false;
						$scope.showtip = "您的积分太少, 不够激活帮客房产哟~";
					}
					$ionicLoading.hide();
		        }, function(error) {
		        }, function(progress) {
		        });
	    		
	            $scope.activemodal = modal;
	            // 返回
	            $scope.closeactivemodal = function(){
					modal.hide();
				}
	            $scope.gobacktomemberhome = function(){
	            		modal.hide();
	            		$state.go("bangke.memberhome", {});
				}
	            // 选择推荐人
	            $scope.referee = {};
	            // 查询推荐人
	            $scope.tosearchreferee = function(){
	            	
			    		$ionicLoading.show({
						content: 'Loading',
						animation: 'fade-in',
						showBackdrop: true,
						maxWidth: 200,
						showDelay: 0
					});
	            		if (undefined == $scope.referee.membername 
	            					|| '' == $scope.referee.membername) {
						$scope.searchmember('平台');
		            } else {
		            		$scope.searchmember($scope.referee.membername);
		            }
				}
	        });
       	}
        
        $scope.searchmember = function(membername){
        		cbdService.getbymembername(membername).then(function(result) {
        			if (undefined != result.Response.Header.ResponseCode 
        				&& 'M' == result.Response.Header.ResponseCode
        				&& undefined != result.Response.Body.Response
        				&& result.Response.Body.Response.length == 1) {
        				
        				// 查询房产推荐人成功, 继续查询该会员是否是房产会员
        				cbdService.ismember(result.Response.Body.Response[0].memberid).then(function(result1) {
        					if (undefined == result1.body.status || '2' != result1.body.status) {
        						// 推荐人不是帮客房产会员, 不允许激活
        						$scope.referee.tip = "您选择的推荐人目前不是帮客房产会员!";
        						$scope.referee.ispass = false;
        					} else {
        						// 推荐人是帮客房产会员, 允许激活
        						$scope.referee = result.Response.Body.Response[0];
        						$scope.referee.ispass = true;
        					}
        					$ionicLoading.hide();
        					if ($scope.referee.ispass) {
        						$scope.referee.gragh = fileurl + $scope.referee.gragh;
		        				// 自定义弹窗
							var mypopup = $ionicPopup.show({
								template: '<div class="content no-header ionic-pseudo writeback memberlist" style="margin: 0 auto;"><div class="list" ><a class="item item-avatar">'
					                + '<img ng-src="{{referee.gragh}}" /><h2>{{referee.membername}}</h2><p>{{referee.tel}}</p></a></div></div>',
								title: '请确认推荐人',
								scope: $scope,
								buttons: [{
										text: '取消'
									}, {
										text: '<b>确定</b>',
										type: 'button-popup',
										onTap: function(e) {
								            // 输入密码
								            $scope.insertpwd();
										}
									}]
							});
							mypopup.then(function(res) {
								angular.element(document.querySelector('.popup-container')).remove();
							});
	        				} else {
	        					alert($scope.referee.tip);
	        				}
    						
    					}, function(error) {
				        }, function(progress) {
				        });
				        
    				} else {
    					// 查询房产推荐人失败: 会员不存在
    					$scope.referee.tip = "会员不存在!";
    					alert($scope.referee.tip);
						$scope.referee.ispass = false;
						$ionicLoading.hide();
    				}
    				// $scope.showcheckrefereemodal();
    				
	        }, function(error) {}, function(progress) {});
        }
        $scope.insertpwd = function(){
	        	
			// 支付密码模态框
			$ionicPopover.fromTemplateUrl('templates/member/cbd/paypwd.html', {
				scope: $scope
			}).then(function(popover) {
				$scope.popover = popover;
				$scope.popover.show();
			});
        }
        
		$scope.securepwd = {};
		$scope.securepwd.securepwd = "";
		$scope.toactive = function(){
	        // 校验安全码
	        cbdService.confirmpayment($scope.securepwd.securepwd).then(function(result) {
	        		if ('01' == result.body.handleStatus
	        			&& userinfoService.getUser().memberid == result.body.memberid
	        			&& 'Y' == result.body.operateStatus
	        			&& 5 > parseInt(result.body.secureerrorcount)) {
	        				
	        			$scope.active();
	        		} else {
	        			alert(result.header.MsgList[0].MsgContent);
	        		}
	        	}, function(error) {
	    			alert("网络错误!");
	    			$scope.popover.remove();
			}, function(progress) {
				
			});
		}
        
        // 确认激活, 进入帮客房产界面
        $scope.active = function(){
        		$scope.popover.remove();
        		$ionicLoading.show({
				content: 'Loading',
				animation: 'fade-in',
				showBackdrop: true,
				maxWidth: 200,
				showDelay: 0
			});
        		// 激活帮客房产, 调用接口
        		$scope.activeresult = {};
        		cbdService.register(userinfoService.getUser().memberid, 
        			$scope.referee.memberid).then(function(result) {
    				
    				$scope.buttontext = "";
    				$scope.activeflag = false;
        			
        			if(undefined != result.body.result && "1" == result.body.result){
        				// 激活成功
        				$scope.activeresult.tip = "恭喜您激活帮客房产成功!";
        				$scope.activeresult.activeflag = true;
        			} else {
        				// 激活失败
        				$scope.activeresult.tip = "激活失败!";
        				$scope.activeresult.activeflag = false;
        			}
        			$scope.activeokmodal.show();
    				$scope.closeactivemodal();
    				
        			$ionicLoading.hide();
    			}, function(error) {
    				
    			}, function(progress) {
    				
    			});
		}
        // 取消激活, 回到会员页面
        $scope.cancelactive = function(){
			modal.hide();
			$scope.closeactivemodal();
			$state.go("bangke.memberhome", {});
		}
        
        // 激活成功结果
        $ionicModal.fromTemplateUrl('templates/member/cbd/activeok.html', {
            scope: $scope
        }).then(function(modal) {
            $scope.activeokmodal = modal;
            $scope.into = function(){
				$scope.activeokmodal.hide();
				$ionicLoading.show({
					content: 'Loading',
					animation: 'fade-in',
					showBackdrop: true,
					maxWidth: 200,
					showDelay: 0
				});
				// 初始化帮客房产数据
				$scope.init('');
				$scope.getfacilitate();
			}
            
            $scope.goback = function(){
				$scope.activeokmodal.hide();
				$scope.closeactivemodal();
				// $scope.closecheckrefereemodal();
				$state.go("bangke.memberhome", {});
			}
        });
        
        // 初始化帮客房产首页数据(不包含我的促成人)
        $scope.init = function(status){
        	
        		cbdService.queryindexinit
        			(userinfoService.getUser().memberid, status).then(function(result) {
        				
				if (undefined != result.header.ResponseCode
						&& "M" == result.header.ResponseCode) {
					$scope.buyinfo = result.body.buyCbdAmount;
					$scope.indexinit = result.body.cbdIndexInit;
					$scope.indexinit.referenceimg = fileurl + $scope.indexinit.referenceimg;
					if (undefined != result.body.status && '1' == result.body.status) {
						$scope.quitflag = true;
					}
					$scope.initflag[0] = true;
					if ($scope.initflag[0] && $scope.initflag[1]) {
						$ionicLoading.hide();
					}
				} else {
					alert(result.header.MsgList[0].MsgContent);
					$ionicLoading.hide();
				}
    			}, function(error) {
    				
    			}, function(progress) {
    				
    			});
        }
        
        // 初始化我的促成人数据
        $scope.getfacilitate = function(){
        		cbdService.queryfacilitatellist
        			(userinfoService.getUser().memberid).then(function(result) {
        				
				if (undefined != result.header.ResponseCode
						&& "M" == result.header.ResponseCode) {
					$scope.facilitate = result.body.myFacilitate;
					//$scope.facilitate = result.body.IndexInit;
					
					$scope.initflag[1] = true;
					if ($scope.initflag[0] && $scope.initflag[1]) {
						$ionicLoading.hide();
					}
				} else {
					alert(result.header.MsgList[0].MsgContent)
				}
    			}, function(error) {
    				
    			}, function(progress) {
    				
    			});
       	}
        // 查看提现记录
        $scope.showtranseout = function(){
        	
			$ionicLoading.show({
				content: 'Loading',
				animation: 'fade-in',
				showBackdrop: true,
				maxWidth: 200,
				showDelay: 0
			});
	        	// 提现记录
	        $ionicModal.fromTemplateUrl('templates/member/cbd/transeout.html', {
	            scope: $scope
	        }).then(function(modal) {
	            $scope.transeoutmodal = modal;
	            			
	            cbdService.selectlstapplyinfo
	            		(userinfoService.getUser().memberid).then(function(result) {
	            		
					if (undefined != result.header.ResponseCode
							&& "M" == result.header.ResponseCode) {
						$scope.drawalsrecords = result.body.lstCbdApplyInfoStc;
						$ionicLoading.hide();
					} else {
						alert(result.header.MsgList[0].MsgContent);
						$ionicLoading.hide();
					}
	    			}, function(error) {
	    				
	    			}, function(progress) {
	    				
	    			});
	    			
	    			$scope.toview = function(item){
		            	// 查看提现记录
			        $ionicModal.fromTemplateUrl('templates/member/cbd/viewtranseout.html', {
			            scope: $scope
			        }).then(function(modal) {
			            $scope.viewtranseoutmodal = modal;
			            $scope.viewtranseoutmodal.show();
			            $scope.drawalsrecord = item;
			        });
	            }
	    			
	    			$scope.transeoutmodal.show();
	        });
        }
        
        $scope.apply.applyAmount = 0;
		var updateSelected = function(action,item){
	        if(action == 'add' && $scope.apply.lstFacilitatekey.indexOf(item.facilitatekey) == -1){
	            $scope.apply.lstFacilitatekey.push(item.facilitatekey);
	            $scope.apply.applyAmount += parseInt(item.bonus);
	        }
	        if(action == 'remove' && $scope.apply.lstFacilitatekey.indexOf(item.facilitatekey)!=-1){
	            var idx = $scope.apply.lstFacilitatekey.indexOf(item.facilitatekey);
	            $scope.apply.lstFacilitatekey.splice(idx, 1);
	            $scope.apply.applyAmount -= parseInt(item.bonus);
	        }
	    }
	
	    $scope.updateSelection = function($event, id){
	        var checkbox = $event.target;
	        var action = (checkbox.checked ? 'add':'remove');
	        updateSelected(action, id, checkbox.name);
	    }
	
	    $scope.isSelected = function(id){
	        return $scope.apply.lstFacilitatekey.indexOf(id) >= 0;
	    }
        
        // 申请单确认
        $ionicModal.fromTemplateUrl('templates/member/cbd/applycomfim.html', {
            scope: $scope
        }).then(function(modal) {
        		$scope.applycomfimmodel = modal;
        		
	        // 点击确认申请
	        $scope.confirmapply = function(){
	        		$scope.apply.memberid = userinfoService.getUser().memberid;
	        		
	        		// 调用接口, 提交申请
	        		cbdService.savebuyapply($scope.apply).then(function(result) {
	        				
					if (undefined != result.header.ResponseCode
							&& "M" == result.header.ResponseCode) {
						// 提交申请成功, 销毁提交申请模态框
						
						$scope.apply = {};
						$scope.img = {};
						$scope.applycomfimmodel.remove();
						$scope.applymodal.remove();
						$scope.applyokmodal.show();
					} else {
						alert(result.header.MsgList[0].MsgContent);
						$ionicLoading.hide();
					}
	    			}, function(error) {
	    				
	    			}, function(progress) {
	    			});
	        }
        });
        
        
        // 提交结果
        $ionicModal.fromTemplateUrl('templates/member/cbd/applyok.html', {
            scope: $scope
        }).then(function(modal) {
            $scope.applyokmodal = modal;
            $scope.complete = function(){
           	 	$scope.applyokmodal.remove();
				$ionicLoading.show({
					content: 'Loading',
					animation: 'fade-in',
					showBackdrop: true,
					maxWidth: 200,
					showDelay: 0
				});
            		// 帮客房产首页初始化
				$scope.init('');
				$scope.getfacilitate();
            		
            }
        });
        
        // 跳转到申请页面
        $scope.toapply = function(){
        		
	    		$ionicLoading.show({
				content: 'Loading',
				animation: 'fade-in',
				showBackdrop: true,
				maxWidth: 200,
				showDelay: 0
			});
			if (0 < parseInt($scope.buyinfo.cashwithdrawal)) {
        			$scope.applyshow = true;
        		}
        		// status: 0 不可提    1 提现    2未提     3提现处理中
        		cbdService.queryfacilitatebystatus
        			(userinfoService.getUser().memberid, '2').then(function(result) {
        				
				if (undefined != result.header.ResponseCode
						&& "M" == result.header.ResponseCode) {
					$scope.applyfacilitate = result.body.myFacilitate;
					
					$timeout(function() {
						$ionicLoading.hide();
					}, 2000);
				} else {
					alert(result.header.MsgList[0].MsgContent);
					$ionicLoading.hide();
				}
    			}, function(error) {
    			}, function(progress) {
    			});
        		
    			// 申请单
	        $ionicModal.fromTemplateUrl('templates/member/cbd/apply.html', {
	            scope: $scope
	        }).then(function(modal) {
	            $scope.applymodal = modal;
	            $scope.applymodal.show();
	            
	            $scope.showcomfim = function(){
	    				// 申请单确认
			        $ionicModal.fromTemplateUrl('templates/member/cbd/applycomfim.html', {
			            scope: $scope
			        }).then(function(modal) {
			        		$scope.applycomfimmodel = modal;
			        		// 显示申请模态框
			        		$scope.applycomfimmodel.show();
			        		
				        // 点击确认申请
				        $scope.confirmapply = function(){
				        		
					    		$ionicLoading.show({
								content: 'Loading',
								animation: 'fade-in',
								showBackdrop: true,
								maxWidth: 200,
								showDelay: 0
							});
							
				        		$scope.apply.memberid = userinfoService.getUser().memberid;
				        		
				        		// 调用接口, 提交申请
				        		cbdService.savebuyapply($scope.apply).then(function(result) {
				        				
								if (undefined != result.header.ResponseCode
										&& "M" == result.header.ResponseCode) {
									// 提交申请成功, 销毁提交申请模态框
									$scope.apply = {};
									$scope.img = {};
									$scope.applycomfimmodel.remove();
									$scope.applymodal.remove();
									$scope.applyokmodal.show();
									
							    		$ionicLoading.hide();
								} else {
									alert(result.header.MsgList[0].MsgContent);
									$ionicLoading.hide();
								}
				    			}, function(error) {
				    			}, function(progress) {
				    			});
				        }
			        });
	            }
	        });
        }
        
        // 查询是否是房产会员
        cbdService.ismember(userinfoService.getUser().memberid).then(function(result) {
	        if (undefined == result.body.status || '2' != result.body.status) {
	        		
	        		$scope.showactivemodal();
	        } else {
	        	
		        // 帮客房产首页初始化
				$scope.init('');
				$scope.getfacilitate();
	        }
	        
        }, function(error) {
        		$scope.showactivemodal();
        		$ionicLoading.hide();
        		$scope.showtip = "尚未上线, 敬请期待~";
        }, function(progress) {
        });
        
        // 退出帮客房产
        $scope.quit = function(){
        		var tippopup = $ionicPopup.show({
				template: '<div style="padding: .15rem;margin-top: .1rem; text-indent: .28rem;">'
								+ '系统将返还激活会员时扣除的积分数, 确定要退出帮客房产吗?</div>',
				title: '系统提示',
				scope: $scope,
				buttons: [{
						text: '取消'
					}, {
						text: '<b>确定</b>',
						type: 'button-popup',
						onTap: function(e) {
				            
				            // 调用接口, 提交申请
				        		cbdService.savequitapply().then(function(result) {
				        				
								if (undefined != result.header.ResponseCode
										&& "M" == result.header.ResponseCode
										&& "1" == result.body.result) {
									alert("申请成功!");
									$state.go("bangke.memberhome", {});
								} else {
									alert(result.header.MsgList[0].MsgContent);
									$ionicLoading.hide();
								}
				    			}, function(error) {
				    			}, function(progress) {
				    			});
						}
					}]
			});
        }
        $scope.cancelapply = function(applykey){
        		// 自定义弹窗
			var mypopup = $ionicPopup.show({
				template: '是否确认提交?',
				title: '系统提示',
				scope: $scope,
				buttons: [{
						text: '取消'
					}, {
						text: '<b>确定</b>',
						type: 'button-popup',
						onTap: function(e) {
				            // 调用接口, 提交撤销申请
				        		cbdService.cancelapply(applykey).then(function(result) {
				        			$ionicLoading.show({
									content: 'Loading',
									animation: 'fade-in',
									showBackdrop: true,
									maxWidth: 200,
									showDelay: 0
								});
								if (undefined != result.header.ResponseCode
										&& "M" == result.header.ResponseCode) {
									alert(result.body.resultExplain);
									$scope.viewtranseoutmodal.remove();
									cbdService.selectlstapplyinfo
						            		(userinfoService.getUser().memberid).then(function(result) {
						            		
										if (undefined != result.header.ResponseCode
												&& "M" == result.header.ResponseCode) {
											$scope.drawalsrecords = result.body.lstCbdApplyInfoStc;
											$ionicLoading.hide();
										} else {
											alert(result.header.MsgList[0].MsgContent);
											$ionicLoading.hide();
										}
						    			}, function(error) {
						    				
						    			}, function(progress) {
						    				
						    			});
								} else {
									alert(result.header.MsgList[0].MsgContent);
									$ionicLoading.hide();
								}
				    			}, function(error) {
				    			}, function(progress) {
				    			});
						}
					}]
			});
			mypopup.then(function(res) {
				angular.element(document.querySelector('.popup-container')).remove();
			});
        		
        }
        
        // 跳转到上传购房凭证
        $scope.openupdatemodel0 = function(){
        		$ionicModal.fromTemplateUrl('templates/member/cbd/uploadcertificate0.html', {
	            scope: $scope
	        }).then(function(modal) {
	            $scope.certificatemodel0 = modal;
	            $scope.certificatemodel0.show();
	        });
        }
        $scope.openupdatemodel1 = function(){
        		$ionicModal.fromTemplateUrl('templates/member/cbd/uploadcertificate1.html', {
	            scope: $scope
	        }).then(function(modal) {
	            $scope.certificatemodel1 = modal;
	            $scope.certificatemodel1.show();
	        });
        }
        $scope.submitupload0 = function(){
			$scope.certificatemodel0.remove();
        }
        $scope.submitupload1 = function(){
			$scope.certificatemodel1.remove();
        }
		
        // 上传组件开始
		$scope.upload = function(){
			var sidebar = document.getElementsByClassName('file-hook');
			angular.element(sidebar)[0].click();
		};
		
		$scope.previewimag0 = function() {
			var base64 = new UploadBase64(event.target, 
				angular.element(document.getElementsByClassName('img-list'))[0], 
				'redpacketrechargeimg', userinfoService.getUser().memberid, "0");
		}
		
		$scope.previewimag1 = function() {
			var base64 = new UploadBase64(event.target, 
				angular.element(document.getElementsByClassName('img-list'))[0], 
				'redpacketrechargeimg', userinfoService.getUser().memberid, "1");
		}
	
		$scope.deleteimg = function() {
		    angular.element(event.target).parent().remove();
		    angular.element(document.querySelector('.img-uploaded'))
				.removeClass("img-uploaded").addClass("img-upload");
		}
		$scope.submitimg = function() {
			$scope.uploadmodal.hide();
		}
		// 上传组件结束
		/**
    		 * 压缩图片后回调函数, 名字不可更改
    		 * @param {Object} filebase64
    		 * @param {Object} name
    		 */
    		$scope.img = {};
    		$scope.uploadfile = function(filebase64, name, index){
    			
			// 加载动画
			$ionicLoading.show({
				content: 'Loading',
				animation: 'fade-in',
				showBackdrop: true,
				maxWidth: 200,
				showDelay: 0
			});
			var imgData = filebase64;
			// 调用接口上传
			commonService.uploadfile(filebase64.substring
					(22, filebase64.length), name).then(function(result) {
						
				if ("M" == result.header.ResponseCode) {
					alert("上传成功!");
					angular.element(document.querySelector('.img-upload'))
						.removeClass("img-upload").addClass("img-uploaded");
						
					if ("0" == index) {
						$scope.img.fileimg0 = imgData;
						$scope.apply.applyVoucher = result.body.filename;
					} else if ("1" == index) {
						$scope.img.fileimg1 = imgData;
						$scope.apply.contractVoucher = result.body.filename;
					}
					return true;
				} else {
					alert(result.body.msg);
					return false;
				}
	        }, function(error) {
	        }, function(progress) {
	        		$ionicLoading.hide();
	        });
    		}
				}
			} else {
				alert(result.header.MsgList[0].MsgContent)
			}
		});
		
    }
]);
bangkeapp.filter('cbdcashstatus', function(){
    return function(status){
        var desc = '';
        if ("0" == status) {
        		desc = "未到期";
        } else if ("1" == status) {
        		desc = "提现";
        } else if ("2" == status) {
        		desc = "未提";
        } else if ("3" == status) {
        		desc = "提现处理中";
        } else {
        		desc = "-";
        } 
        return desc;
    }
});